package org.shj.javaconcurrencypattern.common;

import java.util.concurrent.Callable;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

import org.shj.util.Util;

public class ConditionVarBlocker implements Blocker{
	private final Lock lock;
	private final Condition condition;
	
	public ConditionVarBlocker(Lock lock){
		this.lock = lock;
		this.condition = lock.newCondition();
	}
	
	public ConditionVarBlocker(){
		this.lock = new ReentrantLock();
		this.condition = lock.newCondition();
	}

	@Override
	public <V> V callWithGuard(GuardedAction<V> guardedAction) throws Exception {
		lock.lockInterruptibly();
		V result;
		try{
			final Predicate guard = guardedAction.guard;
			Util.print("broker.callWithGuard()");
			while(!guard.evaluate()){
				condition.await();
			}
			
			Util.print("condition matched. Call real action.");
			result = guardedAction.call();
			condition.signal();
			return result;
		}finally{
			lock.unlock();
		}
	}

	@Override
	public void signalAfter(Callable<Boolean> stateOperation) throws Exception {
		lock.lockInterruptibly();
		try{
			if(stateOperation.call()){
				Util.print("唤醒等待的线程");
				condition.signal();
			}
		}finally{
			lock.unlock();
		}
		
	}

	@Override
	public void signal() throws InterruptedException {
		lock.lockInterruptibly();
		Util.print("signal()");
		try{
			condition.signal();
		}finally{
			lock.unlock();
		}
		
	}

	@Override
	public void broadcastAfter(Callable<Boolean> stateOperation)
			throws Exception {
		lock.lockInterruptibly();
		Util.print("broadcastAfter()");
		try{
			if(stateOperation.call()){
				condition.signalAll();
			}
		}finally{
			lock.unlock();
		}
		
	}
	
	

}
